package com.hyg.module_report.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.bumptech.glide.Glide;
import com.hyg.lib_base.MyView.BodyConstitutionPoint;
import com.hyg.lib_base.MyView.CustomRadarView;
import com.hyg.lib_base.MyView.HealthSystemView;
import com.hyg.lib_base.MyView.PercentPieView;
import com.hyg.lib_base.Net.NetworkOP;
import com.hyg.lib_base.mainUtils.BitmapUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.ossdemo.ProgressInputStream;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.module_report.R;
import com.hyg.module_report.model.HealthReportDetailData;
import com.hyg.module_report.ui.activity.HealthReportActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.FormBody;


public class HealthReportDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private HealthReportActivity context;
    private ArrayList<HealthReportDetailData> dataList;
    private int selectItem = 0;//设置选中点
    private OnItemClickLisener clickListener;
    private MyHandler myHandler;
    private SharedPreferences sn = null;
    private RadioGroup radioGroup;
    private ArrayList<RadioButton> list_radiobutton;
    private SweetAlertDialog pDialogs;
    public static final String accessKeyId = "LTAImEYCt3oofbDP";
    public static final String accessKeySecret = "YczQrsbzVHkm7RC7PyTCBkqnycFMN4";

    public HealthReportDetailAdapter(HealthReportActivity context, ArrayList<HealthReportDetailData> dataList) {
        this.context = context;
        this.dataList = dataList;
        myHandler = new MyHandler();
        sn = this.context.getSharedPreferences("HYG", Context.MODE_PRIVATE);
    }

    public int getSelectItem() {
        return selectItem;
    }

    public void setSelectItem(int selectItem) {
        this.selectItem = selectItem;
    }

    public void addItem(HealthReportDetailData content, int position) {
        dataList.add(position, content);
        notifyItemInserted(position); //Attention!
    }

    public void removeItem(HealthReportDetailData model) {
        int position = dataList.indexOf(model);
        dataList.remove(position);
        notifyItemRemoved(position);//Attention!
    }


    public interface OnItemClickLisener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    public void setOnItemClickLitener(OnItemClickLisener mOnItemClickLitener) {
        this.clickListener = mOnItemClickLitener;
    }

    @Override
    public int getItemViewType(int position) {
        // 适合在添加上拉下拉加载其他页面时使用
        return Integer.parseInt(dataList.get(position).getSummaryType());
        // 本方法在 onCreateViewHolder 之前调用，所以设置 多种布局的类型
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        if (viewType == 0) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_health_report_qushi, parent, false);
            return new HealthTrendViewHolder(view);

        } else if (viewType == 1) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_health_report_summary, parent, false);
            return new SummaryViewHolder(view);

        } else if (viewType == 2) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_health_report_tongue, parent, false);
            return new SheTuViewHolder(view);

        } else if (viewType == 3) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_health_report_pulse, parent, false);
            return new MaiXingViewHolder(view);

        } else if (viewType == 4) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_health_report_tizhi, parent, false);
            return new TiZhiViewHolder(view);
        } else {
            return null;
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
//                holder.itemView.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        clickListener.onItemClick(v, position);
//                    }
//                });
        if (dataList.get(position).getSummaryType().equals("0")) {
            HealthTrendViewHolder viewHolders = (HealthTrendViewHolder) holder;
            viewHolders.bindView(dataList.get(position));

        } else if (dataList.get(position).getSummaryType().equals("1")) {
            SummaryViewHolder viewHolders = (SummaryViewHolder) holder;
            viewHolders.bindView(dataList.get(position));

        } else if (dataList.get(position).getSummaryType().equals("2")) {
            SheTuViewHolder viewHolders = (SheTuViewHolder) holder;
            viewHolders.bindView(dataList.get(position));

        } else if (dataList.get(position).getSummaryType().equals("3")) {
            MaiXingViewHolder viewHolders = (MaiXingViewHolder) holder;
            viewHolders.bindView(dataList.get(position));

        } else if (dataList.get(position).getSummaryType().equals("4")) {
            TiZhiViewHolder viewHolders = (TiZhiViewHolder) holder;
            viewHolders.bindView(dataList.get(position));
        } else {

        }
    }

    public void removeData(int position) {
        dataList.remove(position);
        notifyItemRemoved(position);
    }

    @Override
    public int getItemCount() {
        if (dataList == null) {
            return 0;
        }
        return dataList.size();
    }


    class HealthTrendViewHolder extends RecyclerView.ViewHolder {
        private SeekBar progress_qushi;
        private int process = 0;
        private TextView conclusion;
        private HealthSystemView health_system;

        public HealthTrendViewHolder(View view_qushi) {
            super(view_qushi);

            health_system = (HealthSystemView) view_qushi.findViewById(R.id.health_system);
            conclusion = (TextView) view_qushi.findViewById(R.id.conclusion);
            progress_qushi = (SeekBar) view_qushi.findViewById(R.id.progress);
            progress_qushi.setProgress(process);

        }

        public void bindView(final HealthReportDetailData data) {
            for (BodyConstitutionPoint item : data.getHealthSystemPoints()) {
                process += item.getConversionScore();
            }
            health_system.setData(data.getHealthSystemPoints(), data.getHealthSex());
            progress_qushi.setProgress(process / 9);
            conclusion.setText("\u3000\u3000通过本次体检以及大数据分析:您在全国与您同年龄、同性别的用户中，您的健康状况在每百人中战胜了" + process / 9 + "人。");
        }
    }

    class SummaryViewHolder extends RecyclerView.ViewHolder {
        private TextView tv_summary_advice;

        public SummaryViewHolder(View itemView) {
            super(itemView);
            tv_summary_advice = (TextView) itemView.findViewById(R.id.tv_summary_advice);
        }

        public void bindView(final HealthReportDetailData data) {
            tv_summary_advice.setText("\u3000" + data.getZonghe_advice());
        }
    }

    class SheTuViewHolder extends RecyclerView.ViewHolder {
        private TextView tv_tongue_advice;
        private ImageView img_start_sheti;
        private ImageView img_start_shexia;
        private ImageView img_start_mian;

        private Button sheshen;
        private Button shetai;
        private Button shese;
        private Button shexing;
        private Button taise;
        private Button taizhi;
        private Button shexialuomai;

        private Button zhengtimianse;
        private Button renzhongyanse;
        private Button renzhongxingtai;


        private static final String endpoint = "oss-cn-beijing.aliyuncs.com";
        private static final String bucket = "app-tongue";

//        private RecyclerView rv_sheti_jiexi;

        public SheTuViewHolder(View itemView) {
            super(itemView);
            tv_tongue_advice = (TextView) itemView.findViewById(R.id.tv_tongue_advice);

            img_start_sheti = (ImageView) itemView.findViewById(R.id.img_start_sheti);
            img_start_shexia = (ImageView) itemView.findViewById(R.id.img_start_shexia);
            img_start_mian = (ImageView) itemView.findViewById(R.id.img_start_mian);

            sheshen = (Button) itemView.findViewById(R.id.bt_sheshen);
            shetai = (Button) itemView.findViewById(R.id.bt_shetai);
            shese = (Button) itemView.findViewById(R.id.bt_shese);
            shexing = (Button) itemView.findViewById(R.id.bt_shexing);
            taise = (Button) itemView.findViewById(R.id.bt_taise);
            taizhi = (Button) itemView.findViewById(R.id.bt_taizhi);
            shexialuomai = (Button) itemView.findViewById(R.id.bt_shexialuomai);

            zhengtimianse = (Button) itemView.findViewById(R.id.bt_mianse);
            renzhongyanse = (Button) itemView.findViewById(R.id.bt_renzhongyanse);
            renzhongxingtai = (Button) itemView.findViewById(R.id.bt_renzhongxingtai);
//            miantufenxi = (Button)itemView.findViewById(R.id.miantufenxi);
        }

        public void bindView(final HealthReportDetailData data) {
            if (!Utils.isEmpty(data.getShetufenxi().trim()) && !Utils.isEmpty(data.getMiantufenxi().trim())) {
                tv_tongue_advice.setText("综合建议:\n\u3000\u3000" + data.getShetufenxi().trim() + "\n\u3000\u3000" + data.getMiantufenxi().trim());
            } else {
                tv_tongue_advice.setVisibility(View.GONE);
            }


            Glide.with(context).load(data.getMiantu_url()).into(img_start_mian);
            bindImageView(data.getMiantu_url(), img_start_mian);

            Glide.with(context).load(data.getShetu_url()).into(img_start_sheti);
            bindImageView(data.getShetu_url(), img_start_sheti);

            Glide.with(context).load(data.getShexia_url()).into(img_start_shexia);
            bindImageView(data.getShexia_url(), img_start_shexia);

            if (!Utils.isEmpty(data.getSheshen().trim()))
                sheshen.setText(data.getSheshen().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getShetai().trim()))
                shetai.setText(data.getShetai().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getShese().trim()))
                shese.setText(data.getShese().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getShexing().trim()))
                shexing.setText(data.getShexing().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getTaise().trim()))
                taise.setText(data.getTaise().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getTaizhi().trim()))
                taizhi.setText(data.getTaizhi().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getShexiamailuo().trim()))
                shexialuomai.setText(data.getShexiamailuo().trim().replaceAll("\\|", " "));

            if (!Utils.isEmpty(data.getZhengtimianse().trim()))
                zhengtimianse.setText(data.getZhengtimianse().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getRenzhongyanse().trim()))
                renzhongyanse.setText(data.getRenzhongyanse().trim().replaceAll("\\|", " "));
            if (!Utils.isEmpty(data.getRenzhongxingtai().trim()))
                renzhongxingtai.setText(data.getRenzhongxingtai().trim().replaceAll("\\|", " "));

//            sheshen.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    OnClickRadioButton("舌神",data.getSheshen());
//                }
//            });
//            shetai.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    OnClickRadioButton("舌态",data.getShetai());
//                }
//            });
            shese.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OnClickRadioButton("舌色", data.getShese());
                }
            });
            shexing.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OnClickRadioButton("舌形", data.getShexing());
                }
            });
            taise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OnClickRadioButton("苔色", data.getTaise());
                }
            });
            taizhi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OnClickRadioButton("苔质", data.getTaizhi());
                }
            });

        }

        @SuppressLint("CheckResult")
        public void bindImageView(final String Image_url, ImageView imageView) {

            final int[] progress = {0};
            final Bitmap[] bm = new Bitmap[1];
            //创建RxAndroid线程
            Observable.create(new ObservableOnSubscribe<byte[]>() {
                @Override
                public void subscribe(final ObservableEmitter<byte[]> subscriber) throws Exception {
                    Log.d("oss", "subscribe");
                    Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(context.getExternalFilesDir(null) + Image_url);
                    if (Utils.isEmpty(bitmap)) {//判断文件目录是否存在
                        initOSS(endpoint).asyncGetObject(new GetObjectRequest(bucket, Image_url),
                                new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
                                    @Override
                                    public void onSuccess(final GetObjectRequest request, final GetObjectResult result) {
                                        InputStream inputStream = result.getObjectContent();
                                        //重载InputStream来获取读取进度信息
                                        ProgressInputStream progressStream = new ProgressInputStream(inputStream,
                                                new OSSProgressCallback<GetObjectRequest>() {
                                                    @Override
                                                    public void onProgress(GetObjectRequest o, long currentSize, long totalSize) {
                                                        //                                        Log.d("GetObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                                                        progress[0] = (int) (100 * currentSize / totalSize);
                                                    }
                                                }, result.getContentLength());
                                        try {
                                            Log.d("oss", "progress");
                                            bm[0] = autoResizeFromStream(progressStream, imageView);
                                            //                                    bm = BitmapFactory.decodeStream(progressStream);
                                            if (progress[0] >= 100) {
                                                if (BitmapUtil.saveBitmapToSDCard(bm[0], context.getExternalFilesDir(null) + Image_url)) {
                                                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                                    bm[0].compress(Bitmap.CompressFormat.PNG, 80, baos);
                                                    byte[] bytes = baos.toByteArray();
                                                    if (bm[0] != null) {
                                                        bm[0] = null;
                                                    }
                                                    Log.d("oss", "subscriber");
                                                    subscriber.onNext(bytes);
                                                    //                                            Log.d("oss", "onNext");
                                                }
                                            }
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(GetObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                        Throwable throwable = new Throwable("高清原图片下载失败，请退出重试");
                                        subscriber.onError(throwable);
                                        Log.d("oss", "onFailure");
                                    }
                                });
                    } else {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
                        byte[] bytes = baos.toByteArray();
                        if (bitmap != null) {
                            bitmap.recycle();
                        }
                        subscriber.onNext(bytes);
                    }
                }
            }).subscribeOn(Schedulers.io())//指定数据发射(上方的subscribe方法)在哪个线程执行
                    .observeOn(AndroidSchedulers.mainThread())//observeOn方法决定他下面的方法执行在哪个线程中
                    .subscribe(new Observer<byte[]>() {
                        @Override
                        public void onError(Throwable e) {
                            //                            setToast(e.getMessage());
                        }

                        @Override
                        public void onComplete() {
                            if (context != null) {
                                Glide.with(context.getApplicationContext()).load(context.getExternalFilesDir(null) + Image_url).into(imageView);
                            }
                        }

                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(byte[] res) {
                            if (context != null) {
                                Glide.with(context.getApplicationContext()).load(res).into(imageView);
                            }
                        }
                    });
        }

        public void setToast(String message) {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        }

        //初始化一个OssService用来上传下载
        public OSS initOSS(String endpoint) {
            //        如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            OSS oss = new OSSClient(context, endpoint, credentialProvider, conf);
            Log.d("oss", "initOSS");
            return oss;
        }

        //根据ImageView大小自动缩放图片
        public Bitmap autoResizeFromStream(InputStream stream, ImageView imageView) throws IOException {

            byte[] data;
            {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = stream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
                outStream.close();
                data = outStream.toByteArray();
            }

            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, options);

            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, imageView.getWidth(), imageView.getHeight());
            //            Log.d("ImageHeight", String.valueOf(options.outHeight));
            //            Log.d("ImageWidth", String.valueOf(options.outWidth));
            //            Log.d("Height", String.valueOf(imageView.getWidth()));
            //            Log.d("Width", String.valueOf(imageView.getWidth()));
            //options.inSampleSize = 10;

            //            Log.d("SampleSize", String.valueOf(options.inSampleSize));
            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeByteArray(data, 0, data.length, options);
        }

        //计算图片缩放比例
        public int calculateInSampleSize(
                BitmapFactory.Options options, int reqWidth, int reqHeight) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;

            if (height > reqHeight || width > reqWidth) {

                final int halfHeight = height / 2;
                final int halfWidth = width / 2;

                // Calculate the largest inSampleSize value that is a power of 2 and keeps both
                // height and width larger than the requested height and width.
                while ((halfHeight / inSampleSize) > reqHeight
                        && (halfWidth / inSampleSize) > reqWidth) {
                    inSampleSize *= 2;
                }
            }
            return inSampleSize;
        }
    }


    class MaiXingViewHolder extends RecyclerView.ViewHolder {
        private TextView zonghezhenduan, maizhenduantishi;
        //        private String MaiType = "";
        private RecyclerView RV_pulseDatas;
        private PulseDataAdapter pulseDataAdapter;

        public MaiXingViewHolder(View view_mai) {
            super(view_mai);
            zonghezhenduan = (TextView) view_mai.findViewById(R.id.zonghezhenduan);
            maizhenduantishi = (TextView) view_mai.findViewById(R.id.zhenduantishi);
            RV_pulseDatas = (RecyclerView) view_mai.findViewById(R.id.RV_pulseDatas);

        }

        public void bindView(final HealthReportDetailData data) {
//            SpannableString mx =  new SpannableString("\u3000脉型："+data.getMaixing().trim());
//            mx.setSpan(new ForegroundColorSpan(Color.parseColor("#666666")),0 , 4 , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//            maixing.setText(mx);


            pulseDataAdapter = new PulseDataAdapter(context, data.getPulseDatas());
//            RV_pulseDatas.setNestedScrollingEnabled(false);
            RV_pulseDatas.setLayoutManager(new LinearLayoutManager(context));
//                    DividerItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
//                    RV_pulseDatas.addItemDecoration(itemDecoration);
            RV_pulseDatas.setAdapter(pulseDataAdapter);
            RV_pulseDatas.setItemAnimator(new DefaultItemAnimator());
            zonghezhenduan.setText("脉诊综合诊断提示：\n\u3000\u3000" + data.getMaixiang_zhenduan());

            maizhenduantishi.setText("左手：" + data.getLeft_maixing() + ";\u3000\u3000右手：" + data.getRight_maixing());
            maizhenduantishi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (data.getLeft_maixing().equals("未测")) {
                        OnClickRadioButton("脉型", data.getRight_maixing());
                    } else if (data.getRight_maixing().equals("未测")) {
                        OnClickRadioButton("脉型", data.getLeft_maixing());
                    } else {
                        OnClickRadioButton("脉型", data.getLeft_maixing() + "-" + data.getRight_maixing());
                    }
                }
            });
        }
    }


    class TiZhiViewHolder extends RecyclerView.ViewHolder {
        private ArrayList<BodyConstitutionPoint> Points = new ArrayList<>();
        private TextView bt_main_constitution, bt_secondary_constitution;
        private LinearLayout ll_secondary_constitution;
        private CustomRadarView customRadarView;
        private String MainBody = "";
        private String secondaryBody = "";

        private String PackageSelection = "2";
        private PercentPieView mPercentPieView;
        private String DashujuPhysiqueType = "";
        private TextView dashuju_conclusion;
        private String[] labels = {"平和质", "阳虚质", "阴虚质", "痰湿质", "湿热质", "气虚质", "血瘀质", "气郁质", "特禀质", ""};//标签文本
        //    private Float[] datas = {(float) 32.75, (float) 7.90, (float) 8.89, (float) 6.29, (float) 9.88, (float) 12.71, (float) 7.95, (float) 8.73, (float) 4.91};
        private Float[] datas = {(float) 28.9, (float) 16.4, (float) 5.2, (float) 6.29, (float) 10.2, (float) 13.2, (float) 8, (float) 8.8, (float) 2.5};
        private float physiqueNumber = 0;

        private AnalysisResultAdapter tizhiAnalysisAdapter;
        private RecyclerView rv_tizhi_jiexi;
        private ArrayList<String> Body_name = new ArrayList<>();
        private ArrayList<String> Body_analysis = new ArrayList<>();

        @SuppressLint("WrongViewCast")
        public TiZhiViewHolder(View view_tizhi) {
            super(view_tizhi);
            customRadarView = (CustomRadarView) view_tizhi.findViewById(R.id.radarView);
            bt_main_constitution = (TextView) view_tizhi.findViewById(R.id.bt_main_constitution);
            bt_secondary_constitution = (TextView) view_tizhi.findViewById(R.id.bt_secondary_constitution);
            ll_secondary_constitution = (LinearLayout) view_tizhi.findViewById(R.id.ll_secondary_constitution);

            dashuju_conclusion = (TextView) view_tizhi.findViewById(R.id.dashuju_conclusion);
            mPercentPieView = (PercentPieView) view_tizhi.findViewById(R.id.mPercentPieView);
//            rv_tizhi_jiexi = (RecyclerView)view_tizhi.findViewById(R.id.rv_tizhi_jiexi);
        }

        public void bindView(final HealthReportDetailData data) {
            Points = newGetPoint(data.getPhysique());
            setPointsTitle();
            if (!Utils.isEmpty(MainBody)) {
                bt_main_constitution.setText(MainBody);
                bt_main_constitution.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        OnClickRadioButton("体质", MainBody);
                    }
                });
            }
            if (!Utils.isEmpty(secondaryBody)) {
                ll_secondary_constitution.setVisibility(View.VISIBLE);
                bt_secondary_constitution.setText(secondaryBody);
                bt_secondary_constitution.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        OnClickRadioButton("体质", secondaryBody);
                    }
                });
            } else {
                ll_secondary_constitution.setVisibility(View.GONE);
            }
            customRadarView.setData(Points);

            DashujuPhysiqueType = MainBody + "。" + secondaryBody;
            ArrayList<String> entries = new ArrayList<String>();
            String result = "";
            for (int i = 0; i < datas.length; i++) {
                if (DashujuPhysiqueType.contains(labels[i])) {
                    String txt = labels[i];// + "\n" + datas[i] + "%";
                    //                entries.add(new PieEntry(datas[i], txt)); //
                    entries.add(txt);
                    physiqueNumber = datas[i];
                    result += "\u3000\u3000" + labels[i] + "占全部人群体质中的" + physiqueNumber + "%,\n";
                } else {
                    //                entries.add(new PieEntry(datas[i], ""));
                }
            }
            mPercentPieView.setData(entries);
            //        setPieChartData(entries);
            //        Legend l = mPieChart.getLegend();
            //        colors = l.getColors();
            //        List<LegendEntry> les = new ArrayList<LegendEntry>();
            //        for (int i = 0; i < colors.length; i++) {
            //            LegendEntry legendEntry = new LegendEntry(labels[i], Legend.LegendForm.CIRCLE, 13f, 0f, null, colors[i]);
            //            les.add(legendEntry);
            //        }
            //        l.setCustom(les);
            //        l.setExtra(les);
            //        mPieChart.invalidate();

            if (MainBody.equals("平和质")) {
                dashuju_conclusion.setText(result + "\u3000\u3000您是健康的平和体质，您要继续保持自己的健康哦！");
            } else {
                dashuju_conclusion.setText(result + "\u3000\u3000对比体质检测结果中最棒的平和质，您要为自己的健康加油喽！");
            }

        }
//        public void setRVAnalysisResult(){
//            Body_name.clear();
//            Body_analysis.clear();
//            Body_name.add(MainBody);
//            Body_analysis.add(majorAnalysis);
//            if(!Utils.isEmpty(secondaryBody)) {
//                Body_name.add(secondaryBody);
//                Body_analysis.add(minorAnalysis);
//            }
//            tizhiAnalysisAdapter = new AnalysisResultAdapter(context,Body_name,Body_analysis);
//
//            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
//            rv_tizhi_jiexi.setLayoutManager(linearLayoutManager);
//            rv_tizhi_jiexi.setItemAnimator(new DefaultItemAnimator());
//            tizhiAnalysisAdapter.setHasStableIds(true);
//            rv_tizhi_jiexi.setAdapter(tizhiAnalysisAdapter);
//        }

        public String CalculationResults(String signNumber, ArrayList<BodyConstitutionPoint> Points) {
            MainBody = "";
            secondaryBody = "";
            //商务版体质辨识结果计算
            //平和质得分为 ：P
            //其他体质得分为：Y、Q  ………默认 Y > Q
            //
            //①	、P > 60 && Y < 30 && Q < 30：主要体质为P，次要体质为空
            //②	、P > 60 && Y > 40 && Q > 40：主要体质为Y，次要体质为Q
            //③	、P > 60 && Y > 40 && 30 < Q < 40：主要体质为Y，次要体质为Q
            //④	、P > 60 && 30 < Y < 40 && 30 < Q < 40：主要体质为P，次要体质为Y
            //⑤
            //⑥	、P < 60 && Y < 30 && Q < 30：主要体质为 分数最高体质，次要体质为空
            //⑦	、P < 60 && Y > 40 && Q > 40：主要体质为Y，次要体质为Q
            //⑧	、P < 60 && Y > 40 && 30 < Q < 40：主要体质为Y，次要体质为Q
            //⑨	、P < 60 && 30 < Y < 40 && 30 < Q < 40：主要体质为Y，次要体质为Q
            if (signNumber.equals("2")) {     //进入商务版
                double Pointdatas = Points.get(0).getConversionScore();
                String name = Points.get(0).getBodyConstitutionTypes();
                if (name.equals("平和质")) {
                    if (Points.get(1).getConversionScore() >= 40) {
                        MainBody = Points.get(1).getBodyConstitutionTypes();
                        if (Points.get(2).getConversionScore() >= 30) {
                            secondaryBody = Points.get(2).getBodyConstitutionTypes();
                            //                    } else {  //次要不能是 平和质
                            //                        secondaryBody = Points.get(0).getBodyConstitutionTypes();
                        }
                    } else if (Points.get(1).getConversionScore() < 40 && Points.get(1).getConversionScore() >= 30) {
                        if (Pointdatas >= 60) {
                            MainBody = name;
                            secondaryBody = Points.get(1).getBodyConstitutionTypes();
                        } else {
                            MainBody = Points.get(1).getBodyConstitutionTypes();
                            if (Points.get(2).getConversionScore() >= 30) {
                                secondaryBody = Points.get(2).getBodyConstitutionTypes();
                                //                        } else {  //次要不能是 平和质
                                //                            secondaryBody = Points.get(0).getBodyConstitutionTypes();
                            }
                        }
                    } else {
                        MainBody = name;
                    }
                } else {
                    MainBody = name;
                    if (Points.get(1).getBodyConstitutionTypes().equals("平和质")) {
                        if (Points.get(2).getConversionScore() > 30) {
                            secondaryBody = Points.get(2).getBodyConstitutionTypes();
                        }
                    } else {
                        if (Points.get(1).getConversionScore() > 30) {
                            secondaryBody = Points.get(1).getBodyConstitutionTypes();
                        }
                    }
                }
                //            setAnalyzeDescriptions(MainBody.substring(0, MainBody.length() - 1));

            } else {     ////进入默认 医疗版体质辨识结果
                double maxvalue = 0.0;
                int maxpoint = 0;
                if (!Points.get(0).getBodyConstitutionTypes().equals("平和质")) {
                    maxvalue = Points.get(0).getConversionScore();
                    maxpoint = 0;
                } else {
                    maxvalue = Points.get(1).getConversionScore();
                    if (Points.get(0).getConversionScore() >= 60)
                        maxpoint = 1;
                    else {
                        maxpoint = 2;
                    }
                }//获取除了平和质的最大转化分

                for (int i = 0; i < Points.size(); i++) {
                    double Pointdatas = Points.get(i).getConversionScore();
                    String name = Points.get(i).getBodyConstitutionTypes();
                    if (Pointdatas >= 30)
                        if (name.equals("平和质")) {
                            if (maxvalue < 40 && Pointdatas >= 60) {    //如果当前item是平和质大于60，但是最大分值是其他体质的，主要体质为其他体质
                                MainBody += Points.get(i).getBodyConstitutionTypes() + "、";
                            }
                        } else {
                            if (maxvalue >= 40 && Pointdatas >= 40) {   //如果当前item是其他体质大于40，则主要体质包含该当前item体质
                                MainBody += Points.get(i).getBodyConstitutionTypes() + "、";

                            } else if (maxvalue >= 40 && Pointdatas < 40 && Pointdatas >= 30) { //如果当前item小于40大于30，最大分值大于40，则该item为次要体质
                                secondaryBody += Points.get(i).getBodyConstitutionTypes() + "、";

                            } else if (maxvalue < 40 && Pointdatas < 40 && Pointdatas >= 30 && maxpoint == 2) {//如果当前item小于40大于30，最大分值小于40，则该item为次要体质
                                secondaryBody += Points.get(i).getBodyConstitutionTypes() + "、";

                            } else if (maxvalue < 40 && Pointdatas >= 30 && maxpoint == 1) {//如果当前item大于30，最大分值大于40，则该item为次要体质
                                secondaryBody += Points.get(i).getBodyConstitutionTypes() + "、";

                            }
                        }
                }
            }
            return MainBody + secondaryBody;
        }

        public void setPointsTitle() {
            Collections.sort(Points, new Comparator<BodyConstitutionPoint>() {
                public int compare(BodyConstitutionPoint bean1, BodyConstitutionPoint bean2) {
                    double i1 = bean1.getConversionScore();
                    double i2 = bean2.getConversionScore();
                    //降序排列
                    if (i1 > i2) {
                        return -1;
                    } else if (i1 < i2) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });

            CalculationResults(PackageSelection, Points);
        }

        //获取数据列表
        public ArrayList<BodyConstitutionPoint> newGetPoint(String BCPInfo) {
            ArrayList<BodyConstitutionPoint> _list = new ArrayList<BodyConstitutionPoint>();
            try {
                if (null != BCPInfo && !BCPInfo.equals("null") && !BCPInfo.equals("")) {
                    JSONArray data = new JSONArray(BCPInfo);
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject body = new JSONObject(data.get(i).toString());
                        String name = body.getString("name");
                        String score = body.getString("score");
                        JSONArray result = new JSONArray(body.getString("result"));
                        BodyConstitutionPoint bcp = new BodyConstitutionPoint(
                                "" + name,
                                Double.parseDouble(score),
                                ScroeMeasureMethod(Double.parseDouble(score), result.length()),
                                "" + result.length(),
                                ""
                        );
                        _list.add(bcp);
                    }
                }
            } catch (JSONException e) {
                Log.d(context.CrashTAG, "" + e.getMessage());
            }
            return _list;
        }

        //计算体质得分方式
        public double ScroeMeasureMethod(double scroe, int itemNumber) {
            double changeScroe = ((scroe - itemNumber) * 100 / (itemNumber * 4));
            return changeScroe;
        }
    }

    private class MyHandler extends Handler {
        //自定义handler用来接收从服务器端返回的包装数据
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://个人信息已保存
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
                        //                        Log.d("welcomeadUUM", jsondata + "");
                        if (status.equals("200")) {
                            pDialogs = new SweetAlertDialog(context, SweetAlertDialog.SUCCESS_TYPE);
                            //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                            pDialogs.setTitleText("解析结果");
                            pDialogs.setContentText("\u3000" + message);
                            pDialogs.setConfirmButton("OK", new SweetAlertDialog.OnSweetClickListener() {
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.cancel();
                                }
                            });
                            pDialogs.setCancelable(false);
                            pDialogs.show();

                        } else {
                            pDialogs = new SweetAlertDialog(context, SweetAlertDialog.ERROR_TYPE);
                            //        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                            pDialogs.setTitleText(message);
                            pDialogs.setConfirmButton("我重新试试！", new SweetAlertDialog.OnSweetClickListener() {
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.cancel();
                                }
                            });
                            pDialogs.show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    public void OnClickRadioButton(String name, String data) {
        View view = View.inflate(context, R.layout.dialog_radiobutton, null);
        radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
        list_radiobutton = new ArrayList<RadioButton>();
        String datas = data.trim().replaceAll("\\|", " ");
        if (!Utils.isEmpty(datas) && !datas.equals("null") && !datas.equals("正常")) {
            if (data.substring(0, 1).equals(" ")) {
                data = data.substring(1, data.length()).replaceAll(" ", "-");
            } else {
                data = data.replaceAll(" ", "-");
            }
            if (name.equals("体质")) {
                data = data.replaceAll("、", "-");
            }
            //            Log.d("checkId", "OnClickRadioButton: " + data);
            String[] listdata = data.split("-");
            if (listdata.length != 0) {
                if (listdata.length == 1) {
                    setAnalyzeDescription(data.replaceAll("[^\u4e00-\u9fa5]", " "));
                } else {
                    addRadioview(radioGroup, data, list_radiobutton);
                    pDialogs = new SweetAlertDialog(context, SweetAlertDialog.NORMAL_TYPE);
                    pDialogs.getProgressHelper().setBarColor(Color.parseColor("#7b40be"));
                    pDialogs.setTitleText(name + "结果解析");
                    pDialogs.setCustomView(view);
                    pDialogs.show();
                }
            }
        }
    }

    public void addRadioview(RadioGroup radiogroup, String data, ArrayList<RadioButton> list) {
        int index = 0;
        String[] listdata = data.split("-");
        for (String ss : listdata) {
            if (!ss.trim().equals("")) {
                RadioButton button = new RadioButton(context);
                setRaidBtnAttribute(button, ss.replaceAll("\\|", " "), index + 1);
                //                Log.d("checkId", "addRadioview: " + ss);
                radiogroup.addView(button);
                RadioGroup.LayoutParams layoutParams = (RadioGroup.LayoutParams) button
                        .getLayoutParams();
                layoutParams.setMargins((int) context.getResources().getDimension(R.dimen.font4),
                        (int) context.getResources().getDimension(R.dimen.font4),
                        (int) context.getResources().getDimension(R.dimen.font4),
                        (int) context.getResources().getDimension(R.dimen.font4));//4个参数按顺序分别是左上右下
                button.setLayoutParams(layoutParams);
                index++;
                //            RadioButton btn = (RadioButton)RelativeLayout.findViewById(i);
                list.add(button);
            }
        }
    }

    @SuppressLint("ResourceType")
    private void setRaidBtnAttribute(final RadioButton codeBtn, String btnContent, int id) {
        if (null == codeBtn) {
            return;
        }
        codeBtn.setBackgroundResource(R.drawable.corner_boder_maintheme);
        codeBtn.setTextColor(context.getResources().getColorStateList(R.drawable.color_radiobutton));
        codeBtn.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        codeBtn.setTextSize(14);
        codeBtn.setId(id);
        codeBtn.setText(btnContent);
        codeBtn.setPadding((int) context.getResources().getDimension(R.dimen.font16),
                (int) context.getResources().getDimension(R.dimen.font8),
                (int) context.getResources().getDimension(R.dimen.font16),
                (int) context.getResources().getDimension(R.dimen.font8));
        codeBtn.setGravity(Gravity.CENTER);
        codeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pDialogs.isShowing())
                    pDialogs.dismiss();
                setAnalyzeDescription(codeBtn.getText().toString());
            }
        });
        RadioGroup.LayoutParams rlp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
        codeBtn.setLayoutParams(rlp);
    }

    // 查询解析结果
    public void setAnalyzeDescription(String name) {
        String str_tag = "1";
        FormBody formBody = new FormBody.Builder()
                .add("token", sn.getString("token", ""))//设置参数名称和参数值
                .add("name", name)//设置参数名称和参数值
                .build();
        NetworkOP op = new NetworkOP(str_tag, formBody, myHandler, UrlUtils.analyze_description);
        //使用类的对象op将三个实参发送，通过handler传递参数到NetworkOP中去，在NetworkOP将数据包装发送到规定的互联网地址
        op.okhttpAsyncPost();
    }

}